<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出衣服数据</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除衣服信息
        </el-button>
        <el-button type="success" :icon="CirclePlus" plain @click="addCategory"> 新增大类 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!-- 编辑大类 -->
        <el-button type="primary" link :icon="EditPen" @click="editCategory(scope.row)"> 编辑大类 </el-button>
        <!-- 删除大类 -->
        <el-button type="danger" link :icon="Delete" @click="deleteCategory(scope.row)"> 删除大类 </el-button>
        <!-- 编辑小类 -->
        <el-dropdown trigger="click">
          <el-button type="warning" link>
            编辑小类
            <el-icon><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="sub in scope.row.subCategories"
                :key="sub.id"
                @click="editSubCategory(sub, scope.row.category)"
              >
                {{ sub.typeName }}
              </el-dropdown-item>
              <el-dropdown-item v-if="!scope.row.subCategories.length" disabled>暂无子类</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" link :icon="CirclePlus" @click="openDrawer('新增', scope.row)">新增小类</el-button>
      </template>
    </ProTable>
    <SubAdd ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { Clothes, User } from "@/api/interface";
import { useHandleData, useWarnData } from "@/hooks/useHandleData";
import { useDownload, useDownloads } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import SubAdd from "@/views/clothes/components/SubAdd.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Plus, Upload, View, Refresh } from "@element-plus/icons-vue";
import { deleteListId } from "@/api/modules/users";
import {
  deleteCategoryGroup,
  deleteCategoryType,
  getCategoryExport,
  postCategory,
  postCategoryAdd,
  postCategoryAddType,
  putCategory,
  putCategoryType
} from "@/api/modules/clothes";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";

const hoverTagId = ref<string | null>(null); // 当前鼠标悬停的子类 ID
// ProTable 实例
const proTable = ref<ProTableInstance>();
const initParam = reactive({ type: 1 });
const dataCallback = (data: any) => {
  const baseUrl = import.meta.env.VITE_BACIL_IMG;
  const list = data.records.map((item: any) => {
    if (item.imageUrl && !item.imageUrl.startsWith("http")) {
      item.imageUrl = baseUrl + item.imageUrl;
    }
    return item;
  });
  return {
    list: list,
    total: data.total
  };
};
const getTableList = (params: any) => {
  showFullScreenLoading();
  let newParams = JSON.parse(JSON.stringify(params));
  tryHideFullScreenLoading();
  console.log("object", newParams);
  return postCategory(newParams);
};
// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<Clothes.CategoryStat>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success(`已复制`);
  } catch (err) {
    ElMessage.error("复制失败");
  }
};
// 表格配置项
const columns = reactive<ColumnProps<Clothes.CategoryStat>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "sort", label: "Sort", width: 80 },
  {
    prop: "categoryName",
    label: "大类名称",
    search: { el: "input", tooltip: "我是搜索提示" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.categoryName)}>
          {scope.row.categoryName}
        </el-button>
      );
    }
  },
  {
    prop: "subCategories",
    label: "子类列表",
    render: scope => {
      return scope.row.subCategories.length > 0 ? (
        scope.row.subCategories.map((sub: Clothes.SubCategory) => (
          <el-tag
            style="margin-right: 4px"
            type="success"
            size="small"
            closable={hoverTagId.value === sub.id}
            onClose={() => deleteSubCategory(sub)}
            onMouseenter={() => (hoverTagId.value = sub.id)}
            onMouseleave={() => (hoverTagId.value = null)}
            onClick={() => editSubCategory(sub, scope.row.category)}
          >
            {sub.typeName}
          </el-tag>
        ))
      ) : (
        <span style="color: #aaa">暂无子类</span>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 250 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

//删除子类
const deleteSubCategory = async (sub: Clothes.SubCategory) => {
  await ElMessageBox.confirm(`确定删除子类「${sub.typeName}」吗？`, "提示", { type: "warning" });
  await useHandleData(deleteCategoryType, sub.id, `删除子类「${sub.typeName}」`);
  proTable.value?.getTableList(); // 刷新表格
};
// 编辑大类（可视情况弹窗或 drawer）
const editCategory = async (row: Clothes.CategoryStat) => {
  try {
    const { value } = await ElMessageBox.prompt("请输入新的大类名称", `编辑大类「${row.categoryName}」`, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: row.categoryName,
      inputPattern: /\S+/,
      inputErrorMessage: "分类名不能为空"
    });
    await useHandleData(putCategory, { category: row.category, categoryName: value }, `修改大类名称为「${value}」`);
    proTable.value?.getTableList();
  } catch (e) {
    ElMessage.info("已取消编辑");
  }
};
// 删除大类
const deleteCategory = async (row: Clothes.CategoryStat) => {
  await ElMessageBox.confirm(`确认删除大类「${row.categoryName}」吗？`, "提示", { type: "warning" });
  await useHandleData(deleteCategoryGroup, row.id, `删除大类「${row.categoryName}」`);
  proTable.value?.getTableList(); // 刷新表格
};
// 编辑小类
const editSubCategory = async (sub: Clothes.SubCategory, parentCategory: number) => {
  try {
    const { value: typeName } = await ElMessageBox.prompt(`请输入子类「${sub.typeName}」的新名称：`, "编辑子类", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      inputValue: sub.typeName,
      inputPattern: /\S+/,
      inputErrorMessage: "名称不能为空"
    });
    const existingKeywords = sub.keywords?.join(",") || "";
    const { value: keywordsStr } = await ElMessageBox.prompt(`请输入关键词（多个用 , 分隔）：`, "编辑关键词", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      inputValue: existingKeywords,
      inputPlaceholder: "例如：大衣,冬季,厚",
      inputPattern: /^.*$/,
      inputErrorMessage: ""
    });

    const keywords = keywordsStr
      ? keywordsStr
          .split(",")
          .map(str => str.trim())
          .filter(Boolean)
      : [];

    const params = {
      id: sub.id,
      category: parentCategory,
      typeName,
      keywords
    };

    await useHandleData(putCategoryType, params, `修改子类为「${typeName}」`);
    proTable.value?.getTableList();
  } catch (e) {
    ElMessage.info("已取消编辑");
  }
};
// 新增大类
const addCategory = async () => {
  try {
    const { value: categoryName } = await ElMessageBox.prompt("请输入新大类名称：", "新增大类", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /\S+/,
      inputErrorMessage: "大类名称不能为空"
    });
    const params = {
      category: null,
      categoryName
    };

    await useHandleData(postCategoryAdd, params, `新增大类「${categoryName}」`);
    proTable.value?.getTableList(); // 重新加载表格
  } catch (e) {
    ElMessage.info("已取消新增");
  }
};
// 批量删除衣服信息
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteListId, { id }, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};
// 导出列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出衣服数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownloads(getCategoryExport, "衣服列表", proTable.value?.searchParam)
  );
};

// 批量添加衣服
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof SubAdd> | null>(null);
const openDrawer = (title: string, row: Partial<Clothes.CategoryStat> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title == "新增" ? postCategoryAddType : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
